package com.nix.web.controller.user;


import com.nix.Exception.PermissionException;
import com.nix.email.ApacheMailSendSimpleEmail;
import com.nix.constant.Consts;
import com.nix.untils.encryption.MD5;
import com.nix.web.controller.BaseController;
import com.nix.web.controller.until.verification.VerificationCode;
import com.nix.web.databases.pojo.user.Info;
import com.nix.web.databases.pojo.user.User;
import com.nix.web.databases.pojo.word.MarkWord;
import com.nix.web.service.user.UserServiceImpl;
import org.apache.commons.mail.EmailException;
import com.nix.web.databases.service.word.MarkWordService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import sun.misc.BASE64Encoder;
import sun.rmi.runtime.Log;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangpei
 * @Email zhangpe0312@qq.com
 * @day 2017/12/7 22:50
 * @Use
 */
@RequestMapping("/user")
@Controller
public class UserController extends BaseController {
    //用户服务类
    @Autowired
    private UserServiceImpl userService;

    //MD5加密类
    @Autowired
    private MarkWordService markWordService;

    @Autowired
    private MD5 md5;

    //验证码生成类
    @Autowired
    private VerificationCode verificationCode;

    private Logger logger = Logger.getLogger(UserController.class);

    /**
     * 登陆控制器
     *
     * @param login
     * @param user
     * @param model
     * @param session
     * @return
     */
    @RequestMapping(value = "/from", method = {RequestMethod.POST})
    public String login(@RequestParam("islogin") String login, User user, Model model,
                        HttpSession session) {

        System.out.println(user.toString() + "\n" +
                "islogin = " + login + "\n" +
                "istrue " + !login.equals("from_login") + "\n ");
        //如果不是从登陆界面进来的，那么拒绝访问
        if (!login.equals("from_login")) {
            return "/app/user/login";
        }

        try {
            user = userService.login(user.getName(), user.getPassword());
        } catch (Exception e) {
            System.err.println("用户 " + user.getName() + " 登陆失败" + e);
            return "/app/user/login";
        }

        if (user == null) {
            model.addAttribute("Notice", "<script type=\"text/javascript\">\n" +
                    "   var con = confirm(\"账号或者密码错误，你需要找回密码么？\");\n" +
                    "   if(con==true){\n" +
                    "       location.href=\"/view/app/user/verification.jsp\";\n" +
                    "   }else{\n" +
                    "       \n" +
                    "   }\n" +
                    "</script>");
            return "/app/user/login";
        }
        if (user.getEnable() != 1) {
            //用户被冻结，不能使用
            model.addAttribute("Notice", "<script type=\"text/javascript\">\n" +
                    " alert(\"你的账号已经冻结，请联系管理员\");\n" +
                    "</script>");
            return "/app/user/login";
        }
        // 获取用户权限信息
        try {
            user = userService.getUserPermission(user.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (user == null) {
            throw new PermissionException();
        }

        //将用户加入session
        session.setAttribute("user", user);
        //将数据传入index.jsp页面验证
        model.addAttribute("user", user);

//        System.out.println("id -- >" + user.getId());
        Integer markCount;
        Integer microBlogCount;
        MarkWord[] words;
        try {
            logger.info("userid " + user.getId());
            markCount = markWordService.getMarkCountById(user.getId());
            microBlogCount = markWordService.getMarkWeiboCountById(user.getId());
            words = markWordService.getMarkWord(user.getId(), Consts.WORD_MARK_REPETITIONS, Consts.WORD_MARK_SEARCH_COUNT, "名词");

            model.addAttribute("words", words);
            model.addAttribute("markCount", markCount);
            model.addAttribute("microBlogCount", microBlogCount);

//            for (MarkWord word : words) {
//                System.out.println(word.toString());
//            }
        } catch (Exception e) {
            System.out.println("查询数据库失败！");
            e.printStackTrace();
        }

        return "/app/word/mark";
    }

    /**
     * 注册控制器
     *
     * @param email
     * @param user
     * @param model
     * @return
     */
    @RequestMapping(value = "/register", method = {RequestMethod.GET, RequestMethod.POST})
    public String register(@RequestParam("email") String email, User user, Model model) {

        try {
            Info userInfo = new Info();
            userInfo.setEmail(email);
            user.setInfo(userInfo);
            userService.register(user);
            userService.addRole(user.getId(), 2);

        } catch (Exception e) {
            //用户被冻结，不能使用
            model.addAttribute("Notice", "<script type=\"text/javascript\">\n" +
                    " alert(\"注册失败，你注册的账号已经存在！\");\n" +
                    "</script>");
            return "/app/user/register";
        }

        model.addAttribute("Notice", "<script type=\"text/javascript\">\n" +
                " alert(\"欢迎你正式加入情绪分析团队。\");\n" +
                "</script>");

        return "/app/user/login";
    }

    /**
     * 邮箱验证控制器
     *
     * @param email
     * @param isVerification
     * @param session
     * @param model
     * @return
     */
    @RequestMapping(value = "/verification", method = {RequestMethod.GET, RequestMethod.POST})
    public String verification(@RequestParam("email") String email,
                               @RequestParam("isVerification") String isVerification,
                               HttpSession session, Model model) {

        if (!isVerification.equals("verification")) {
            model.addAttribute("Notice", "<script type=\"text/javascript\">\n" +
                    " alert(\"请你重申请页面进入申请密码找回！\");\n" +
                    "</script>");
            return "/app/user/verification";
        }

        //发送邮件给这个email 并将生成的验证码保存在此处返回给前端吟唱域，但是需要对验证码加密
        String ecode;
        ecode = verificationCode.getCode();

        ApacheMailSendSimpleEmail sendEmail;
        try {
            sendEmail = new ApacheMailSendSimpleEmail(email, "亲爱的情绪分析朋友！");
            sendEmail.setMsg("你申请的验证码为：" + ecode);
            sendEmail.setSubject("找回密码验证码-情绪分析团队");
            sendEmail.setToAddress(email);
            sendEmail.setToName("你好！");
            try {
                sendEmail.sendEmail();
            } catch (EmailException e) {
                System.out.println("发送邮件失败" + e);

                model.addAttribute("Notice", "<script type=\"text/javascript\">\n" +
                        " alert(\"发送邮件失败！请联系管理员。\");\n" +
                        "</script>");
                return "/app/user/verification";
            }
        } catch (IOException e) {
            System.out.println("发送信息失败！" + e);

            model.addAttribute("Notice", "<script type=\"text/javascript\">\n" +
                    " alert(\"发送邮件失败！请联系管理员。\");\n" +
                    "</script>");
            return "/app/user/verification";
        }
        md5.setUppercase(false);
        ecode = md5.encryption(ecode);
        model.addAttribute("trueValue", ecode);
        model.addAttribute("myEmail", email);
        session.setAttribute("email", email);


        model.addAttribute("Notice", "<script type=\"text/javascript\">\n" +
                " alert(\"请验收你的邮箱信息，并将验证码填入验证框。\");\n" +
                "</script>");

        return "/app/user/verification";
    }

    /**
     * 重置密码控制器
     *
     * @param password
     * @param session
     * @param reset
     * @param model
     * @return
     */
    @RequestMapping(value = "/reset", method = {RequestMethod.GET, RequestMethod.POST})
    public String resetPassword(@RequestParam("password") String password
            , HttpSession session, @RequestParam("isReset") String reset, Model model) {

        if (!reset.equals("reset")) {
            model.addAttribute("Notice", "<script type=\"text/javascript\">\n" +
                    " alert(\"请你重申请页面进入申请密码找回！\");\n" +
                    "</script>");
            return "/app/user/verification";
        }

        //通过邮件找到用户原来的ID
        String email;
        try {
            email = (String) session.getAttribute("email");
            if (email == null) {
                model.addAttribute("Notice", "<script type=\"text/javascript\">\n" +
                        " alert(\"请你重申请页面进入申请密码找回！\");\n" +
                        "</script>");
                return "/app/user/verification";
            }
        } catch (Exception e) {
            System.out.println("查找用户失败！" + e);
            model.addAttribute("Notice", "<script type=\"text/javascript\">\n" +
                    " alert(\"请你重申请页面进入申请密码找回！\");\n" +
                    "</script>");
            return "/app/user/verification";
        }

        //更新用户密码
        Integer userID = userService.getUserIdByEmail(email);
        User user;
        try {
            user = userService.select(userID);
        } catch (Exception e) {
            System.out.println("查找用户失败！" + e);
            model.addAttribute("Notice", "<script type=\"text/javascript\">\n" +
                    " alert(\"查找用户失败\");\n" +
                    "</script>");
            return "/app/user/verification";
        }
        user.setPassword(password);
        try {
            userService.update(user);
        } catch (Exception e) {
            System.out.println("更新用户失败！" + e);
            model.addAttribute("Notice", "<script type=\"text/javascript\">\n" +
                    " alert(\"更新新密码错误！\");\n" +
                    "</script>");
            return "/app/user/verification";
        }
        model.addAttribute("Notice", "<script type=\"text/javascript\">\n" +
                " alert(\"恭喜你改密成功！\");\n" +
                "</script>");
        return "/app/content/index";
    }

}
